<template>
  <div class="login-container">
    <h1>疆屿后台管理</h1>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="login-form">
      <el-form-item prop="username">
        <el-input
          v-model="ruleForm.username"
          placeholder="请输入用户名"
          :clearable="true"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.password"
          placeholder="请输入密码"
          :clearable="true"
          type="password"
          :show-password="true"
        ></el-input>
      </el-form-item>
      <div class="checkbox-group">
        <div class="remember-password-div">
          <input
            type="checkbox"
            :checked="ruleForm.isRemember"
            @click="changeRemember"
          />
          <label for="remember">记住密码</label>
        </div>
        <a href="#" class="forgot-password">忘记密码？</a>
      </div>
      <el-form-item>
        <el-button
          class="login-btn"
          type="primary"
          @click="submitForm('ruleForm')"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { backstorgLogin } from "@/request/user";
import { mapActions, mapGetters } from "vuex";
export default {
  name: "LoginPage",
  data() {
    return {
      ruleForm: {
        username: "",
        password: "",
        isRemember: false,
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },

  mounted() {
    const storedUsername = localStorage.getItem("username");
    const storedPassword = localStorage.getItem("password");
    if (storedUsername && storedPassword) {
      this.ruleForm.username = storedUsername;
      this.ruleForm.password = storedPassword;
      this.ruleForm.isRemember = true;
    }
  },

  computed: {
    ...mapGetters(["isUserLoggedIn"]), // 映射获取登录状态的getter，方便在模板中使用
  },

  methods: {
    ...mapActions(["loginSuccess"]),
    // 改变记住密码的选项状态
    changeRemember() {
      this.ruleForm.isRemember = !this.ruleForm.isRemember;
    },

    // 记住密码
    rememberPassword() {
      // 假设这里是登录验证逻辑，验证成功后（登录成功之后再执行）
      // console.log(this.ruleForm.isRemember)
      if (this.ruleForm.isRemember) {
        localStorage.setItem("username", this.ruleForm.username);
        localStorage.setItem("password", this.ruleForm.password);
      } else {
        localStorage.removeItem("username");
        localStorage.removeItem("password");
      }
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 请求后端登录接口
          const data = {
            username: this.ruleForm.username,
            password: this.ruleForm.password,
          };
          backstorgLogin(data)
            .then(async (res) => {
              // console.log(res);
              if (res.code === 10000) {
                // console.log("登录成功！");
                this.rememberPassword();
                // 更新登录状态
                await this.loginSuccess(res.data.token);// 使用await确保action执行完成
                this.$message.success('登录成功');
                // console.log(this.isUserLoggedIn)
                // 跳转主页
                this.$router.push("/");
              } else {
                this.$message.error(res.message);
              }
            })
            .catch((err) => {
              console.log(err);
              this.$message.error("系统异常");
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  background-color: rgba(194, 215, 232, 0.5);
  background-image: linear-gradient(
    to bottom,
    rgba(79, 205, 224, 0.5) 0%,
    rgba(54, 101, 137, 0.1) 100%
  );
  background-size: cover;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

h1 {
  margin-bottom: 20px;
  color: #333;
  font-size: 24px;
}

.login-form {
  width: 400px;
  height: 200px;
  padding: 30px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: rgba(255, 255, 255, 0.8);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  align-content: center;
}

.checkbox-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.forgot-password {
  color: #666;
  text-decoration: none;
}

.login-btn {
  width: 400px;
  height: 40px;
  background-color: #007bff;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 3px;
  margin-top: 20px;
}
</style>
